package com.stark.lab.covid19statistics.controller;

import com.stark.lab.covid19statistics.dto.RegionStats;
import com.stark.lab.covid19statistics.dto.Result;
import com.stark.lab.covid19statistics.util.DataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/stats")
public class StatsController {

    @Autowired
    DataUtil dataUtil;

    /**
     * 获取国家名称列表
     * @return
     */
    @GetMapping("/list/country")
    public Result getCountryList(){
        List<RegionStats> list = dataUtil.getRegionStatsList();
        Set<String> ret = list.stream().map(RegionStats::getCountry).collect(Collectors.toSet());
        return Result.success(ret);
    }

    /**
     * 获取所有国家的最新统计数据
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/country")
    public Result getAllCountryStats(){
        Map<String,Integer> ret = new HashMap<>();
        dataUtil.getRegionStatsList().stream().collect(Collectors.groupingBy(RegionStats::getCountry))
                .forEach((k, regionStatsList) -> {
                    ret.put(k,regionStatsList.stream().mapToInt(RegionStats::getLatestTotalCases).reduce(Integer::sum).getAsInt());
                });

        return Result.success(ret);
    }

    /**
     * 获取某个国家的最新的疫情统计数据
     * @param country
     * @return
     */
    @GetMapping("/country/{country}")
    public Result getACountryStats(@PathVariable("country")String country){
        return Result.success(
                dataUtil.getRegionStatsList().stream()
                        .filter(a->a.getCountry().equals(country))
                        .mapToInt(RegionStats::getLatestTotalCases)
                        .reduce(Integer::sum));
    }

    /**
     * 获取某个国家里的所有省份的疫情统计数据
     * @param country
     * @return
     */
    @GetMapping("/province/{country}")
    public Result getACountryProvinceStats(@PathVariable("country")String country){
        Map<String,Integer> ret = new HashMap<>();
        dataUtil.getRegionStatsList().stream()
                .filter(a->a.getCountry().equals(country))
                .collect(Collectors.groupingBy(RegionStats::getProvince))
                .forEach((k, regionStatsList) -> {
                    ret.put(k,regionStatsList.stream().mapToInt(RegionStats::getLatestTotalCases).reduce(Integer::sum).getAsInt());
                });

        return Result.success(ret);
    }

}
